/**
 * @author Yuliy Khorolinskyy
 *
 * Reaktionsspiel challengesManager
 *
 * 24.01.2012
 */
package challengesManager;

import java.awt.BorderLayout;

import javax.swing.JPanel;

import challengeGUI.ChallengeGUI;
import challengeGUI.FindTheSameGUI;

import control.Control;
import data.ChallengeData;
import data.Player;

/**
 * @author Yuliy
 *
 */
public class ChallengeManagerAdapter<GuiT extends ChallengeGUI> extends ChallengeManager {

	
	protected GuiT gui;
	protected JPanel placeHolderP;
	protected int pointsDistributed = 0;
	protected boolean buzzEventHasOccured;
	protected boolean processingPlayerAction = false;
	/**
	 * @param c
	 * @param d
	 */
	public ChallengeManagerAdapter(Control c, ChallengeData d) {
		super(c, d);
		setState(STATE_LOADING);
	}

	/* (non-Javadoc)
	 * @see challengesManager.ChallengeManager#start()
	 */
	@Override
	public void start() {
			setState(STATE_RUNNING);
			gui.newRound();
	}

	/* (non-Javadoc)
	 * @see challengesManager.ChallengeManager#playerBuzz(data.Player)
	 */
	@Override
	public void playerBuzz(Player pl) {
	processingPlayerAction = true;
	int revealMsg;
		c.playerHasPressed(pl);
		if(!buzzEventHasOccured){
			gui.freeze();
			pl.setPoints(pl.getPoints() - 1);
			revealMsg = -1;
		}else{
			gui.freeze();
			pl.setPoints(pl.getPoints() + 1);
			++pointsDistributed;
			revealMsg = 1;
		}

		gui.reveal(revealMsg);

	}

	/* (non-Javadoc)
	 * @see challengesManager.ChallengeManager#perfectBuzzMoment(boolean)
	 */
	@Override
	public void perfectBuzzMoment(boolean state) {
		this.buzzEventHasOccured = state;

	}

	/* (non-Javadoc)
	 * @see challengesManager.ChallengeManager#animationOver()
	 */
	@Override
	public void animationOver() {
		if(this.pointsDistributed < d.getRounds()){
			buzzEventHasOccured = false;
			gui.newRound();
		}else{
			setState(STATE_FINISHED);
		}
		c.updateScores();
		this.processingPlayerAction = false;
		this.enableBuzzing();
	}

	/* (non-Javadoc)
	 * @see challengesManager.ChallengeManager#disposeGui()
	 */
	@Override
	public void disposeGui() {
		gui.end();
		placeHolderP.remove(gui);
	}
	
	/**
	 * Has to be overridden!
	 */

	/* (non-Javadoc)
	 * @see challengesManager.ChallengeManager#initGui(javax.swing.JPanel)
	 */
	@Override
	public void initGui(JPanel placeHolderPanel) {
		this.placeHolderP = placeHolderPanel;
		this.placeHolderP.add(this.gui, BorderLayout.CENTER);
		pointsDistributed = 0;
		setState(STATE_LOADED_AND_READY);
	}
	
	@Override
	public void disableBuzzing(){
		c.disableBuzzing();
	}
	
	@Override
	public void enableBuzzing(){
		if(!processingPlayerAction)c.enableBuzzing();
	}

}
